import { constantRoutes } from '@/router'
import Layout from '@/layout'
import { GetUserMenuTree } from '@/api/auth'
// 根据后端得到的原始路由json转换成vue可以挂载的路由json
export function generateMenu(routes, menus) {
  menus.forEach(item => {
    const menu = {
      path: item.route,
      name: item.name,
      meta: { title: item.name, icon: item.icon ?? 'table',id: item.id,parentId:item.parentId, type: item.type },
      children: []
    }
    if(item.path){
      menu.component = (resolve) => require([`@/views${item.path}`], resolve) 
    }else{
      if(item.type == 0 && item.parentId==0){
        menu.component = Layout
      }else{
        if(item.children && item.children.length > 0){
          if(item.children[0].path){
            menu.component = (resolve) => require([`@/views${item.children[0].path}`], resolve)
          }
        }else{
          menu.hidden = true
        }
      }
    }
    if (item.children && item.children.length > 0) {
      generateMenu(menu.children, item.children)
    } else {
      delete menu.children
    }
    routes.push(menu)
  })
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, token) {
    return new Promise(resolve => {
      GetUserMenuTree().then((data)=>{
        let accessedRoutes = []
        generateMenu(accessedRoutes, data.data.children)
        accessedRoutes.push({ path: '*', redirect: '/404', hidden: true })
        commit('SET_ROUTES', accessedRoutes)
        resolve(accessedRoutes)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

